package main

import (
	"airport_container/data_sync"
	"airport_container/data_sync/db"
	"context"
	pb "gitee.com/airport_container/grpc_interface/gosdk/data_sync"
	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	log "github.com/sirupsen/logrus"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"google.golang.org/grpc"
	"net"
	"net/http"
	"os"
	"strconv"
	"time"
)

func main() {
	LogInit()

	syncInterval := 30
	str := os.Getenv("SYNC_INTERVAL")
	if str != "" {
		syncInterval, _ = strconv.Atoi(str)
	}
	syncCloudImg := true
	str = os.Getenv("SYNC_CLOUD_IMG")
	if str == "False" {
		syncCloudImg = false
	}
	//mongoDB init
	//如果在同的docker compose文件可以配置:sacs:sacskfcsacs@db:27017
	dbUrl := os.Getenv("DB_URL")
	if dbUrl == "" {
		dbUrl = "sacs:sacskfcsacs@120.78.130.252:27017"
	}
	clientOptions := options.Client().ApplyURI("mongodb://" + dbUrl)

	ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
	mgoClient, err := mongo.Connect(ctx, clientOptions)
	if err != nil {
		log.Panic("mongo connect:", err)
	}
	defer mgoClient.Disconnect(ctx)
	if err = mgoClient.Ping(ctx, nil); err != nil {
		log.Panic("mongo ping:", err)
	}
	dbStore := db.NewMgoStore(mgoClient)
	//grpc register
	gs := grpc.NewServer()
	pb.RegisterDataSyncServer(gs, data_sync.NewServe(dbStore, syncInterval, syncCloudImg))

	//开启服务
	listen, err := net.Listen("tcp", ":8000")
	if err != nil {
		log.Panic(err)
	}
	go func() {
		if err := gs.Serve(listen); err != nil {
			log.Panic(err)
		}
	}()

	log.WithFields(log.Fields{"syncInterval": syncInterval, "syncCloudImg": syncCloudImg}).Info("data sync serve start success")
	runGw()
}

func runGw() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	mux := runtime.NewServeMux()
	opts := []grpc.DialOption{grpc.WithInsecure()}
	err := pb.RegisterDataSyncHandlerFromEndpoint(ctx, mux, ":8000", opts)
	if err != nil {
		log.Panic("runGw device:", err)
	}

	err = http.ListenAndServe(":9000", mux)
	if err != nil {
		log.Panic("http listen:", err)
	}
}

func LogInit() {
	customFormatter := new(log.TextFormatter)
	customFormatter.TimestampFormat = "2006-01-02 15:04:05.000"
	customFormatter.FullTimestamp = true
	customFormatter.ForceColors = true
	log.SetFormatter(customFormatter)

	//设置log等级
	logLevel, err := log.ParseLevel(os.Getenv("LOG_LEVEL"))
	if err != nil {
		logLevel = log.DebugLevel
	}
	log.SetLevel(logLevel)
}
